<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCategory">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格，在main.js注册了该插件 -->
      <tree-table
        class="tree-table"
        :data="category_data.list"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        :border="true"
      >
        <!-- 这里的slot='status' 对应template='status'， scope接收这一行的数据 -->
        <template slot="status" slot-scope="scope">
          <i
            :class="scope.row.status ? 'el-icon-success' : 'el-icon-error'"
            :style="scope.row.status ? 'color:green' : 'color:red'"
          ></i>
        </template>
        <!-- level排序 -->
        <template slot="level" slot-scope="scope">
          <el-tag
            :type="scope.row.level > tags.length ? tags[scope.row.level % 5] : tags[scope.row.level-1]"
          >{{scope.row.level}}级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="operation" slot-scope="scope">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="small"
            @click="editCategory(scope.row.id)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="deleteCategory(scope.row.id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="category_data.total"
      ></el-pagination>
    </el-card>
    <!-- 添加分类的会话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCategoryDialogVisible"
      width="600px"
      @close="addCategoryDialogClosed"
      center
    >
      <el-form
        :model="addCategoryForm"
        label-width="80px"
        status-icon
        :rules="addCategoryFormRules"
        ref="addCategoryFormRef"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addCategoryForm.name" placeholder="分类名称"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- obtions 指定数据源； -->
          <!-- props  指定配置对象 -->
          <el-cascader
            style="width:100%;"
            placeholder="(可选)父级品类"
            :options="parentCategoryList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="cascaderChange"
            filterable
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategorySubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑品类 的会话框 -->
    <el-dialog
      title="编辑品类"
      :visible.sync="editCategoryDialogVisible"
      width="600px"
      @close="editCategoryDialogClosed"
      center
    >
      <el-form
        :model="editCategoryForm"
        label-width="100px"
        status-icon
        :rules="editCategoryFormRules"
        ref="editCategoryRef"
      >
        <el-form-item label="原品类名称" prop="name">
          <el-input v-model="editCategoryInfo.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新品类名称" prop="newname">
          <el-input v-model="editCategoryForm.newname" placeholder="填写新品类名称"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="categoryID">
          <!-- obtions 指定数据源； -->
          <!-- props  指定配置对象 -->
          <el-cascader
            style="width:100%;"
            placeholder="(可选)默认为原品类父级"
            :options="parentCategoryList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="cascaderChange"
            filterable
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCategorySubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取商品分类数据的参数
      queryInfo: {
        pageNum: 1,
        pageSize: 5
      },
      // 商品分类的数据，包括数据列表与分页信息
      category_data: {},
      // tree-table 的列数据定义
      columns: [
        {
          // 列标题名称
          label: '品类名称',
          // 列数据
          prop: 'name',
          // 列的最小宽度
          minWidth: '100px'
        },
        {
          label: '是否有效',
          prop: 'status',
          // 引入模板
          type: 'template',
          // 当前这一列使用的模板名称，这里对应tree-table里面的slot='status'
          template: 'status',
          minWidth: '100px'
        },
        {
          label: '排序',
          prop: 'level',
          type: 'template',
          template: 'level',
          minWidth: '100px'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation',
          minWidth: '200px'
        }
      ],
      tags: ['', 'success', 'info', 'warning', 'danger'],
      // 添加分类 对话框的显示
      addCategoryDialogVisible: false,
      // 添加分类的数据
      addCategoryForm: {
        name: '',
        parentID: 0
      },
      // 添加分类的规则
      addCategoryFormRules: {
        name: [
          {
            required: 'true',
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ]
      },
      // 父级分类的列表
      parentCategoryList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        // value 选中的值，这里指向所选的id
        value: 'id',
        // label 选择器显示的值
        label: 'name',
        // 级联关系
        children: 'children',
        checkStrictly: true
      },
      // 选中的父级分类的ID数组
      selectedKeys: [],
      // 编辑品类的 显示
      editCategoryDialogVisible: false,
      // 编辑品类的 规则
      editCategoryFormRules: {
        newname: [
          {
            validator: (rule, value, callback) => {
              if (value === this.editCategoryInfo.name) {
                callback(new Error('与原名称相同'))
              }
              if ((value === null || value.trim() === '') && this.selectedKeys.length === 0) {
                callback(new Error('至少有一个新值才能提交！'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        categoryID: [
          {
            validator: (rule, value, callback) => {
              if (this.selectedKeys.length !== 0 && this.selectedKeys[this.selectedKeys.length - 1] === this.editCategoryInfo.id) {
                return callback(new Error('不能放在原分类下，这会导致该分类断层！'))
              }
              callback()
            }
          }
        ]
      },
      // 编辑品类提交的 表单数据
      editCategoryForm: {
        newname: null,
        id: 0,
        parentID: 0
      },
      // 获取需要编辑的品类数据
      editCategoryInfo: {}
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    // 获取商品分类数据
    async getCategoryList() {
      const { data: res } = await this.$axios.get('manage/category/get_category_page', {
        params: this.queryInfo
      })
      if (res.status !== 0) return this.$message.error(res.msg)
      this.category_data = res.data
    },
    //
    async addCategory() {
      const { data: res } = await this.$axios.get('manage/category/get_category_all')
      if (res.status !== 0) return this.$message.error(res.msg)
      this.parentCategoryList = res.data
      this.addCategoryDialogVisible = true
    },
    // 修改编辑分类，根据Id
    async editCategory(id) {
      // 获取需要编辑的品类信息
      const { data: res } = await this.$axios.get('manage/category/select_category/' + id)
      if (res.status !== 0) return this.$message.error(res.msg)
      this.editCategoryInfo = res.data
      // 获取所有分类节点信息
      const { data: res1 } = await this.$axios.get('manage/category/get_category_all')
      if (res1.status !== 0) return this.$message.error(res1.msg)
      this.parentCategoryList = res1.data
      // 打开会话框
      this.editCategoryDialogVisible = true
    },
    // 删除分类，根据id
    deleteCategory(id) {
      this.$confirm('此操作将永久删除该品类，是否继续？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message.success('执行删除操作！')
          const { data: res } = await this.$axios.delete('manage/category/delete_category/' + id)
          if (res.status !== 0) return this.$message.error(res.msg)
          this.$message.success(res.msg)
          this.getCategoryList()
        })
        .catch(() => {
          this.$message.info('取消删除操作！')
        })
    },
    // @size-change 监听 和 处理 页码大小变动时触发的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getCategoryList()
    },
    // @current-change 监听 和 处理 当前页变动时触发的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getCategoryList()
    },
    // 级联选择器内容变动时触发
    cascaderChange() {
      if (this.selectedKeys.length > 0) {
        this.addCategoryForm.parentID = this.selectedKeys[this.selectedKeys.length - 1]
        return
      }
      this.addCategoryForm.parentID = 0
    },
    // 添加品类会话框关闭时，重置相关内容
    addCategoryDialogClosed() {
      this.selectedKeys = []
      this.addCategoryForm = {
        name: '',
        parentID: 0
      }
    },
    // 添加品类 提交
    addCategorySubmit() {
      this.$refs.addCategoryFormRef.validate(async valid => {
        if (!valid) return
        const info = new FormData()
        info.append('name', this.addCategoryForm.name)
        info.append('parentID', this.addCategoryForm.parentID)
        const { data: res } = await this.$axios.post('manage/category/insert_category', info)
        if (res.status !== 0) return this.$message.error(res.msg)
        this.$message.success(res.msg)
      })
    },
    // 编辑品类 提交
    editCategorySubmit() {
      // 首先，校验表单
      this.$refs.editCategoryRef.validate(async valid => {
        if (!valid) return
        // 接着，检查父ID的变化
        if (this.selectedKeys.length === 0) {
          this.editCategoryForm.parentID = this.editCategoryInfo.parentId
        } else {
          this.editCategoryForm.parentID = this.selectedKeys[this.selectedKeys.length - 1]
        }
        const info = new FormData()
        info.append('id', this.editCategoryInfo.id)
        info.append('parentID', this.editCategoryForm.parentID)
        info.append('newname', this.editCategoryForm.newname)
        // 再然后，提交表单
        const { data: res } = await this.$axios.post('manage/category/update_category', info)
        if (res.status !== 0) return this.$message.error(res.msg)
        this.$message.success(res.msg)
        this.editCategoryDialogVisible = false
        this.getCategoryList()
      })
    },
    // 编辑品类 关闭
    editCategoryDialogClosed() {
      this.$refs.editCategoryRef.resetFields()
      this.editCategoryInfo = {}
      this.editCategoryForm = {
        newname: '',
        id: ''
      }
      this.selectedKeys = []
    }
  }
}
</script>

<style lang="less" scoped>
</style>
